package com.fhnew.app.util;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.FileProvider;


import com.fhnew.app.BuildConfig;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * 版本管理
 * <p>
 * 1、检测是否有新版本 {@link VersionManager#versionCheck}
 * 2、下载新版本 {@link VersionManager#downLoadAPP}
 * 3、安装新版本 {@link VersionManager#installAPK}
 */
public class VersionManager {

    private DownLoadListener downLoadListener;

    private DownloadManager downloadManager;

    private long downloadId = 0;

    private String address;

    /**
     * @param context
     * @param nVersion     版本号
     * @param nVersionName 版本名
     * @return
     */
    public boolean versionCheck (Context context, int nVersion, String nVersionName) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo info = null;
        try {
            info = packageManager.getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (info == null) {
            return false;
        }

        if (info.versionCode < nVersion) {
            return true;
        }

        List<String> versionNameList = split(info.versionName);
        List<String> nVersionNameList = split(nVersionName);
        try {
            for (int i = 0; i < versionNameList.size(); i++) {
                if (Integer.parseInt(versionNameList.get(i)) < Integer.parseInt(nVersionNameList.get(i))) {
                    return true;
                }
            }
        } catch (Exception e) {
            //避免解析失败造成的数组下表越界
            HLog.E(HLog.stackTrace() + "  " + e.toString());
            return false;
        }
        return false;
    }

    private List<String> split (String arg) {
        if (arg == null) {
            return null;
        }
        List<String> list = new ArrayList<>();

        int oldIndex = 0;
        int newIndex = 0;

        while ((newIndex = arg.indexOf('.', oldIndex)) >= 0) {
            String v = arg.substring(oldIndex, newIndex);
            list.add(v);
            oldIndex = newIndex + 1;
        }
        String v = arg.substring(oldIndex);
        list.add(v);
        return list;
    }

    /**
     * 开始下载
     */
    public void downLoadAPP (Context context, String url) {

        downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        try {
            request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("?")));
        } catch (Exception e) {
            request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, url);
        }

        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE| DownloadManager.Request.NETWORK_WIFI);

        request.setAllowedOverRoaming(true);
        request.setAllowedOverMetered(true);

        request.setTitle("下载");
        request.setDescription("正在下载最新版本APP应用");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        request.setMimeType("application/vnd.android.package-archive");

        downloadId = downloadManager.enqueue(request);

        handler.postDelayed(refresgRunnable, 200);

    }

    private Handler handler = new Handler();

    private Runnable refresgRunnable = new Runnable() {
        @Override
        public void run () {
            if (downLoadListener != null) {
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadId);
                Cursor cursor = downloadManager.query(query);
                if (cursor == null) {
                    HLog.I("查询不到结果进度");
                }
                if (cursor != null && cursor.moveToFirst()) {
                    int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                    if (status == DownloadManager.STATUS_RUNNING) {
                        //下载的文件地址
                        address = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                        //已经下载的字节数
                        long bytes_downLoad = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                        //总共需要下载的字节数
                        long bytes_downloaded = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

                        float progress = (bytes_downLoad / 1024.0f) / (bytes_downloaded / 1024.0f) * 100;

                        downLoadListener.progress(progress);
                        handler.postDelayed(refresgRunnable, 200);
                    } else if (status == DownloadManager.STATUS_FAILED) {
                        downLoadListener.finish(null);
                    } else if (status == DownloadManager.STATUS_SUCCESSFUL) {
                        downLoadListener.finish(address);
                    }
                }
            }
        }
    };

    public static void installAPK (Context context, String fileSavePath) {
        if(fileSavePath == null)return;

        fileSavePath = fileSavePath.substring(fileSavePath.indexOf("file:/") + 7);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File apkFile = new File(fileSavePath);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(context, BuildConfig.authorities2, apkFile);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    public void setDownLoadListener (DownLoadListener downLoadListener) {
        this.downLoadListener = downLoadListener;
    }

    public interface DownLoadListener {

        public void progress (float progress);

        public void finish (String dir);
    }

}
